using System;
using System.Collections.Generic;
using System.Text;
using MCromwell.StaffIntranet.Task.Tasks;
using MCromwell.StaffIntranet.DTO;
using MCromwell.StaffIntranet.DependencyInjection;

namespace MCromwell.StaffIntranet.Presenters
{
    public class StaffManagementPresenter
    {
        private IStaffManagementView managementView;
        private IStaffViewingTask viewingTask;
        private IStaffManagementTask managementTask;
        
        public StaffManagementPresenter(IStaffManagementTask managementTask, IStaffViewingTask viewingTask, IStaffManagementView managementView)
        {
            if (managementTask == null)
                throw new ArgumentNullException("managementTask", "managementTask cannot be null");

            if (viewingTask == null)
                throw new ArgumentNullException("viewingTask", "viewingTask cannot be null");

            if (managementView == null)
                throw new ArgumentNullException("view", "view cannot be null");

            this.managementView = managementView;
            this.viewingTask = viewingTask;
            this.managementTask = managementTask;

            BindToViewEvents();
        }

        public StaffManagementPresenter(IStaffManagementView view)
            : this(IoC.Resolve<IStaffManagementTask>(), IoC.Resolve<IStaffViewingTask>(), view)
        {
            
        }

        private void BindToViewEvents()
        {
            managementView.Initialize += new EventHandler<StaffManagementInitializeEventArgs>(HandleViewInitialization);
            managementView.StaffSaved += new EventHandler<StaffSavedEventArgs>(HandleStaffSavedEvent);
        }

        void HandleStaffSavedEvent(object sender, StaffSavedEventArgs e)
        {
            NotificationDTO saveNotification = null;
            int staffId = managementTask.SaveChangesUsing(e.Details, out saveNotification);
            managementView.ResultsOfSave(staffId, saveNotification);
        }

        void HandleViewInitialization(object sender, StaffManagementInitializeEventArgs e)
        {
            IList<LocationDTO> locations = viewingTask.RetrieveAvailableLocations();
            managementView.DisplayAvailable(locations);

            if (e.StaffId.HasValue)
            {
                StaffDTO staffToManage = viewingTask.RetrieveStaffDetailsFor(e.StaffId.Value);
                if (staffToManage != null)
                    managementView.ShowDetailsOf(staffToManage);
            }
        }

        
    }
}
